package com.pds.web.industry.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pds.web.device.entity.PdsTestOrganizationDevice;
import com.pds.web.industry.entity.Industry;
import com.pds.web.industry.mapper.IndustryMapper;
import com.pds.web.industry.service.IndustryService;
import com.pds.web.industry.vo.IndustryVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndustryServiceImpl extends ServiceImpl<IndustryMapper, Industry> implements IndustryService {

    @Resource
    private IndustryMapper industryMapper;

    @Override
    public Map selectList() {
        List<Industry> industryList = industryMapper.selectList(null);
        List<IndustryVO> industryVOList = BeanUtil.copyToList(industryList, IndustryVO.class);
        List<IndustryVO> firstList = makeIndustryTree(industryVOList);
        Map result = new HashMap();
        result.put("industryList", firstList);
        return result;
    }

    /**
     * 根据id查询行业类型
     * @param industryId
     * @return
     */
    @Override
    public Industry getIndustryById(String industryId) {
        QueryWrapper<Industry> wrapper = new QueryWrapper<>();
        wrapper.eq("industry_id", industryId);
        return industryMapper.selectOne(wrapper);
    }

    private List<IndustryVO> makeIndustryTree(List<IndustryVO> industryVOList){
        List<IndustryVO> firstList = new ArrayList<>();
        if(!Objects.isNull(industryVOList) && !industryVOList.isEmpty()){
            firstList = industryVOList.stream().filter(i -> i.getLevel().intValue() == 1).collect(Collectors.toList());
            List<IndustryVO> secondList = industryVOList.stream().filter(i -> i.getLevel().intValue() == 2).collect(Collectors.toList());
            List<IndustryVO> threeList = industryVOList.stream().filter(i -> i.getLevel().intValue() == 3).collect(Collectors.toList());
            for (IndustryVO industryVO : secondList){
                List<IndustryVO> children = threeList.stream().filter(s -> s.getParentId().equals(industryVO.getIndustryId())).collect(Collectors.toList());
                industryVO.setChildren(children);
            }
            for (IndustryVO industryVO : firstList){
                List<IndustryVO> children = secondList.stream().filter(s -> s.getParentId().equals(industryVO.getIndustryId())).collect(Collectors.toList());
                industryVO.setChildren(children);
            }
        }
        return firstList;
    }
}
